const express = require('express');
const router = express.Router();
const mongo = require('../dataBase/db');
const multer = require('multer');
const setting = require('../config/generateId');
const myDate = require('../config/date');
const fs = require("fs");

let upload = multer({ dest: './static/upTemp' }).any();

router.post('/', (req, res) => {
    let videoTitle = req.body.videoTitle;
    let videoInfo = req.body.videoInfo;
    let time = req.body.videoTime;
    let videoId = setting.generateVideoId(videoTitle, videoInfo);
    upload = multer({ dest: `./static/video/${videoId}` }).any();
    let videoPag = {
        pubUserId: req.body.userId,
        videoId: videoId,
        title: videoTitle,
        info: videoInfo,
        views: 0,
        time: time,
        videoUrl: "",
        coverUrl: "",
        pubTime: myDate.getYMD()
    }
    new mongo.video(videoPag).save((err, docu) => {
        if (err) throw err;
        res.send({ status: true, videoId: videoId });
    })
});

router.post('/uploadImg', upload, (req, res) => {
    var oldName = req.files[0].filename;
    var fileName = req.files[0].fieldname;
    var type = req.files[0].mimetype;
    var src = `./static/upTemp/${oldName}`;
    type = type.slice(6, type.length);
    let newPath = `./static/video/${fileName}/cover.${type}`;
    let coverUrl = `video/${fileName}/cover.${type}`;
    fs.rename(src, newPath, function(err) {
        if (err) throw err;
        if (!err) {
            // mongo.video.update({ videoId: fileName }, { coverUrl: coverUrl }, (err, row) => {
            //     if (err) throw err;
            //     console.log(row);
            //     res.send({ status: true });
            // })
            mongo.video.findOneAndUpdate({ videoId: fileName }, { coverUrl: coverUrl }).then(data => {
                res.send({ status: true });
            })
        }
    })
});
router.post('/uploadVid', upload, (req, res) => {
    var oldName = req.files[0].filename;
    var fileName = req.files[0].fieldname;
    var type = req.files[0].mimetype;
    var src = `./static/upTemp/${oldName}`;
    type = type.slice(6, type.length);
    let newPath = `./static/video/${fileName}/video.${type}`;
    let videoUrl = `video/${fileName}/video.${type}`
    fs.rename(src, newPath, function(err) {
        if (err) throw err;
        if (!err) {
            mongo.video.update({ videoId: fileName }, { videoUrl: videoUrl }, (err, row) => {
                if (err) throw err;
                res.send({ status: true });
            })
        }
    })
});

router.get('/getVideo', async(req, res) => {
    let videoId = req.query.videoId;
    let resV = await mongo.video.findOne({ videoId: videoId });
    if (resV != null) {
        let userId = resV.pubUserId;

        //访问量+1
        resV.views++;
        let resV2 = await mongo.video(resV).save((err, docu) => {
            if (err) throw err;
        })
        let videoBag = {
            id: videoId,
            url: resV.videoUrl,
            views: resV.views,
            title: resV.title,
            info: resV.info,
            pubDate: resV.pubTime,
            promulgator: {
                userId: userId,
                name: "",
                avatarImg: "",
                fans: 0
            }
        }
        let resU = await mongo.users.findOne({ userId: userId });
        if (resU != null) {

            //返回视频的详情信息

            videoBag.promulgator.name = resU.name;
            videoBag.promulgator.fans = resU.fans.length;
            videoBag.promulgator.avatarImg = resU.avatarImg;

            //判断用户是否已经点赞收藏

            res.send({ status: true, content: '成功', body: videoBag });
        }
    } else {
        res.send({ status: false, content: "未找到视频源" })
    }
})

router.get('/getVideoIndex', async(req, res) => {
    let result = await mongo.video.find({});
    console.log(result);
    if (result != null) {
        let videoList = [];
        result.forEach(item => {
            let videoBag = {
                videoCover: item.coverUrl,
                views: item.views,
                time: `${parseInt(item.time/60)}:${parseInt(item.time%60)}`,
                title: item.title,
                videoId: item.videoId,
                type: '生活区'
            }
            videoList.push(videoBag);
        })
        res.send({ status: true, content: "success", videoList: videoList })
    } else {
        res.send({ status: false, content: '库内暂无视频资源' });
    }
})
module.exports = router;